﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace newcj_routerperformancemonitor.Core
{
    internal class TerminalManager
    {
        public static async Task<Terminal[]> Find(string gateway)
        {
            return await Task.Run(() =>
            {
                if (string.IsNullOrEmpty(gateway) ||
!gateway.Contains('.')) return new Terminal[0];

                var ipParts = gateway.Split('.');
                if (ipParts.Length != 4) return new Terminal[0];

                var ipBase = string.Format("{0}.{1}.{2}.", ipParts[0], ipParts[1], ipParts[2]);
                int ipGatewayPart4 = -1;
                int.TryParse(ipParts[3], out ipGatewayPart4);
                if (ipGatewayPart4 == -1) return new Terminal[0];

                int ipPart4 = 0;
                var ipList = new List<Terminal>();
                while (++ipPart4 < 255)
                {
                    if (ipPart4 == ipGatewayPart4) continue;

                    var ip = ipBase + ipPart4;
                    if (CheckIsConnected(ip))
                    {
                        ipList.Add(new Terminal(ip));
                    }
                }
                return ipList.ToArray();
            });
        }

        private static bool CheckIsConnected(string ip)
        {
            if (string.IsNullOrEmpty(ip)) return false;

            var ping = new Process();
            ping.StartInfo.FileName = "ping.exe";
            ping.StartInfo.UseShellExecute = false;
            ping.StartInfo.RedirectStandardInput = true;
            ping.StartInfo.RedirectStandardOutput = true;
            ping.StartInfo.RedirectStandardError = true;
            ping.StartInfo.CreateNoWindow = true;
            ping.StartInfo.Arguments = string.Format("{0} -n 1 -w 50", ip);
            ping.Start();

            string result = ping.StandardOutput.ReadToEnd();

            if (string.IsNullOrEmpty(result)) return false;

            return result.Contains("ms");
        }
    }

    public class Terminal
    {
        public string Ip { get; private set; }

        internal Terminal(string ip)
        {
            Ip = ip;
        }
    }
}
